<?php
    class Permissao extends BaseModel
    {
    	
    	protected $permissaoid;
    	protected $operacaoid;
        protected $perfilid;
        
        const tablename = 'permissoes';
        const tablekey = 'permissaoid';
        const tablesequence = 'permissoes_permissaoid_seq';

        public function inserirBloco( $bloco, $perfilid )
        {
            try
            {
                pg_query(conexao::Conectar(), "begin");
                
                foreach ( $bloco as $b ){
                	
                	$permissao = new Permissao();
                	$permissao->operacaoid = $b;
                	$permissao->perfilid = $perfilid;
                	$permissao->inserir();
                	
                }

                pg_query(conexao::Conectar(), "commit");
            }
            catch (Exception $ex)
            {
                pg_query(conexao::Conectar(), "rollback");
                echo $ex->getMessage();
            }
        }

        public static function excluirPorPerfil( $perfilid )
        {
        	$sql = "DELETE FROM " . self::tablename . " WHERE perfilid = $perfilid";
            pg_query(conexao::Conectar(), $sql) or die ("Erro ao excluir.");
        }
        
        
	     public function isAuthorizedMenu ( $perfilid, $menu ){
	        	
	        	$o = new Operacao();
	        	
	        	$result = $o->listar( array( 'where' => "descricao like '$menu/%'" ) );
	        	$total =  pg_num_rows( $result );
	        	
	        	# Menu não existe
	        	if ( $total == 0 )
	        		return true;
				
	        	for($i=0;$i<$total;$i++){
	        		$obj = pg_fetch_object($result);
		        	if ( $_SESSION['permissoes'] ){        		
		        		foreach ( $_SESSION['permissoes'] as $p )
		        			if ( $p['operacaoid'] == $obj->operacaoid )
		        				return true;        		
		        	}	        		
	        	}     	
	        	return false;       	
		}
        
        
        public function isAuthorized ( $perfilid, $operacao ){
        	
        	$o = new Operacao();
        	
        	$result = $o->listar( array( 'precondicao' => 'descricao ILIKE \'' . $operacao . '%\'' ) );
        	
        	# Operação não existe
        	if ( pg_num_rows( $result ) == 0 )
        		return true;

        	$result = pg_fetch_object( $result, 0 );
        	
        	if ( $_SESSION['permissoes'] ){
        		
        		foreach ( $_SESSION['permissoes'] as $p )
        			if ( $p['operacaoid'] == $result->operacaoid )
        				return true;
        		
        	}
        	
        	return false;
        	
			/*
        	$sql = "SELECT count(*) as total FROM " . self::tablename . " WHERE operacaoid = " . $result->operacaoid . " AND perfilid = " . $perfilid;
        	
        	$result = pg_fetch_object( pg_query ( conexao::Conectar(), $sql ) );
        	
        	if ( $result->total == 0 )
        		return false;
        	
        	return true;
        	*/
        	
        }
        
    }
?>